#!/bin/sh

BIN_KERNEL="kernel.bin"
DISK_INITRD="initrd.img"
TEMP_CD="cdrom"
GRUB_DIR="GRUB"
OS_DIR="OS"
FILES_DIR="files"

GRUB_PATH="$TEMP_CD/boot/grub"
GRUB_CONF="$GRUB_PATH_CD/grub.cfg"
MENU_CONF="$GRUB_DIR/CD/grub.cfg"
PATH_KERNEL="$TEMP_CD/root"
PATH_INITRD="$TEMP_CD/initrd"
KERNEL="$OS_DIR/release/$BIN_KERNEL"
KERNEL_CD="$PATH_KERNEL/$BIN_KERNEL"
INITRD="$OS_DIR/disk_initrd/$DISK_INITRD"
INITRD_CD="$PATH_INITRD/$DISK_INITRD"
lable="MOS"

sudo fdisk -l

echo "Please input name for flash disk or HDD: "
number=""
read number
test ! -d "/dev/$number" || sudo umount "/dev/$number"
echo "Formating /dev/$number..."
sudo mkfs.vfat -F 32 -n $lable -I "/dev/$number"

echo "Prepare disk:"
echo "    Create temp directory for files which will write on image..."
test -d $TEMP_CD || mkdir $TEMP_CD
echo "    Create directory for GRUB..."
test ! -d "$TEMP_CD/boot" || rm -R "$TEMP_CD/boot"
mkdir "$TEMP_CD/boot"
mkdir "$TEMP_CD/boot/grub"
echo "    Copy grub.cfg on image..."
if [ -w $MENU_CONF ]; then if [ -w $GRUB_CONF ]; then rm $GRUB_CONF ; fi ; cp -R $MENU_CONF $GRUB_CONF ; fi
echo "    Copy directory for kernel..."
test -d $PATH_KERNEL || mkdir $PATH_KERNEL
echo "    Remove old kernel..."
if [ -w $KERNEL_CD ]; then rm $KERNEL_CD ; fi
echo "    Copy kernel..."
cp -R $KERNEL $KERNEL_CD
echo "    Copy directory for initrd..."
test -d $PATH_INITRD || mkdir $PATH_INITRD
echo "    Remove old initrd image..."
if [ -w $INITRD_CD ]; then rm $INITRD_CD ; fi
echo "    Copy initrd image..."
cp -R $INITRD $INITRD_CD
echo "    Copy files on cd..."
test ! -d $FILES_DIR || cp -R "$FILES_DIR/*" $TEMP_CD
echo "    Creating usb..."

test ! -d "/media/$lable" || sudo umount "/media/$lable"
sudo mount "/dev/$number" "/media/$lable"
sudo grub-install --root-directory="/media/$lable" --no-floppy --recheck --force "/dev/$number"
#cp -R "$TEMP_CD/*" "/media/$lable"
rm -R $TEMP_CD
